import { useRef, useSyncExternalStore } from 'react';
import type { TypedKey } from '../context/types';
import { globalContext } from '../globalContext';
import { shallowEqual } from '../utils/shallowEqual';

export function useSelect<T, R>(
  key: TypedKey<T>,
  selector: (value: T) => R,
  equalityFn: (a: R, b: R) => boolean = shallowEqual,
): R {
  // 使用React 18的useSyncExternalStore优化性能
  const selectedValue = useSyncExternalStore(
    // 订阅函数
    (onStoreChange) => {
      const unsubscribe = globalContext.subscribe(key, (_newValue) => {
        onStoreChange();
      });
      return unsubscribe;
    },
    // 获取当前值并应用选择器
    () => {
      const value = globalContext.getData(key);
      return selector(value);
    },
    // 获取服务器端渲染的初始值
    () => {
      const value = globalContext.getData(key);
      return selector(value);
    },
  );

  // 使用ref保存前一个值，只有当值真正变化时才返回新值
  const stableValueRef = useRef(selectedValue);

  if (!equalityFn(stableValueRef.current, selectedValue)) {
    stableValueRef.current = selectedValue;
  }

  return stableValueRef.current;
}
